<template>
  <view class="payment-type-stats-container">
    <z-paging 
      ref="paging" 
      v-model="dataList" 
      @query="queryList"
      :auto="false"
      :refresher-enabled="true"
      :loading-more-enabled="true"
      :empty-view-text="'暂无数据'"
      class="list-paging"
    >
      <template #top>
        <!-- 页面标题 -->
        <view class="page-header">
          <view class="header-title">订单支付统计</view>
        </view>
        
        <!-- 筛选区域 -->
        <view class="filter-section">
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">统计周期：</text>
              <picker mode="selector" :value="filters.periodIndex" :range="periodOptions" @change="onPeriodChange">
                <view class="date-picker">
                  <text>{{ filters.periodIndex >= 0 ? periodOptions[filters.periodIndex] : '请选择' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
            
            <view class="filter-item">
              <text class="filter-label">交易类型：</text>
              <picker :value="filters.transactionTypeIndex" :range="transactionTypes.map(item => item.name)" @change="onTransactionTypeChange">
                <view class="date-picker">
                  <text>{{ filters.transactionTypeIndex >= 0 ? transactionTypes[filters.transactionTypeIndex].name : '全部' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-actions">
            <button class="search-btn" @click="searchData">查询</button>
            <button class="reset-btn" @click="resetFilters">重置</button>
          </view>
        </view>
        
        <!-- 统计摘要 -->
        <view class="summary-section">
          <view class="summary-card">
            <view class="summary-title">总交易金额</view>
            <view class="summary-value">{{ summary.totalAmount }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">总交易笔数</view>
            <view class="summary-value">{{ summary.totalCount }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">平均交易金额</view>
            <view class="summary-value">{{ summary.avgAmount }}</view>
          </view>
        </view>
        
        <!-- 列表表头 -->
        <view class="list-header">
          <text class="list-cell">支付类型</text>
          <text class="list-cell">交易类型</text>
          <text class="list-cell">交易金额</text>
          <text class="list-cell">交易笔数</text>
        </view>
      </template>
      
      <!-- 列表内容 -->
      <view v-for="(item, index) in dataList" :key="index" class="list-row" @click="openDetail(item)">
        <view class="list-cell payment-cell">
          <view class="payment-icon" :style="{ backgroundColor: item.iconBgColor }">{{ item.iconText }}</view>
          {{ item.paymentTypeName }}
        </view>
        <view class="list-cell transaction-cell">
          <view class="transaction-tag" :class="item.transactionType === 'payment' ? 'payment-tag' : 'refund-tag'">
            {{ item.transactionType === 'payment' ? '支付' : '退款' }}
          </view>
        </view>
        <text class="list-cell">{{ item.amount }}元</text>
        <text class="list-cell">{{ item.count }}笔</text>
      </view>
    </z-paging>
    
    <!-- 详情弹窗 -->
    <view class="detail-modal" v-if="showDetailModal">
      <view class="detail-content">
        <view class="detail-header">
          <text class="detail-title">{{ currentDetail ? currentDetail.paymentTypeName + ' 详情' : '详情信息' }}</text>
          <text class="close-btn" @click="showDetailModal = false">×</text>
        </view>
        
        <view class="detail-body" v-if="currentDetail">
          <view class="detail-item">
            <text class="detail-label">支付类型：</text>
            <view class="detail-value payment-detail">
              <view class="payment-icon" :style="{ backgroundColor: currentDetail.iconBgColor }">{{ currentDetail.iconText }}</view>
              {{ currentDetail.paymentTypeName }}
            </view>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">交易类型：</text>
            <view class="detail-value">
              <view class="transaction-tag" :class="currentDetail.transactionType === 'payment' ? 'payment-tag' : 'refund-tag'">
                {{ currentDetail.transactionType === 'payment' ? '支付' : '退款' }}
              </view>
            </view>
          </view>
          

          
          <view class="detail-item">
            <text class="detail-label">统计周期：</text>
            <text class="detail-value">{{ periodOptions[filters.periodIndex] }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">交易金额：</text>
            <text class="detail-value">{{ currentDetail.amount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">交易笔数：</text>
            <text class="detail-value">{{ currentDetail.count }}笔</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">占比：</text>
            <text class="detail-value">{{ currentDetail.percentage }}%</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">平均交易金额：</text>
            <text class="detail-value">{{ currentDetail.avgAmount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">最高交易金额：</text>
            <text class="detail-value">{{ currentDetail.maxAmount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">最低交易金额：</text>
            <text class="detail-value">{{ currentDetail.minAmount }}元</text>
          </view>
          

          
          <view class="detail-item" v-if="currentDetail.parkingLots && currentDetail.parkingLots.length > 0">
            <text class="detail-label">停车场分布：</text>
            <view class="detail-value">
              <view v-for="(lot, idx) in currentDetail.parkingLots" :key="idx" class="lot-item">
                {{ lot.name }}: {{ lot.count }}笔 ({{ lot.percentage }}%)
              </view>
            </view>
          </view>
          
          <view class="detail-item" v-if="currentDetail.timeDistribution && currentDetail.timeDistribution.length > 0">
            <text class="detail-label">时段分布：</text>
            <view class="detail-value">
              <view v-for="(time, idx) in currentDetail.timeDistribution" :key="idx" class="time-item">
                {{ time.name }}: {{ time.count }}笔 ({{ time.percentage }}%)
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'

// 筛选表单
const filters = reactive({
  periodIndex: 0,
  transactionTypeIndex: -1
})

// 统计周期选项
const periodOptions = [
  '日统计',
  '月统计',
  '年统计'
]

// 停车场选项已移除

// 交易类型
const transactionTypes = [
  { name: '全部', value: 'all' },
  { name: '支付', value: 'payment' },
  { name: '退款', value: 'refund' }
]

// 支付类型 - 保留但不在筛选中使用
const paymentTypes = [
  { name: '微信支付', value: 'wechat', icon: 'wechat', iconText: '微', iconBgColor: '#07C160' },
  { name: '支付宝', value: 'alipay', icon: 'alipay', iconText: '支', iconBgColor: '#1677FF' },
  { name: '银联', value: 'unionpay', icon: 'unionpay', iconText: '银', iconBgColor: '#E60012' },
  { name: '钱包余额', value: 'wallet', icon: 'wallet', iconText: '余', iconBgColor: '#FF9500' },
  { name: '月卡', value: 'card', icon: 'card', iconText: '卡', iconBgColor: '#5856D6' },
  { name: '现金', value: 'cash', icon: 'cash', iconText: '现', iconBgColor: '#8E8E93' }
]

// 列表数据
const dataList = ref([])
const paging = ref(null)

// 统计摘要数据
const summary = reactive({
  totalAmount: '0.00',
  totalCount: 0,
  avgAmount: '0.00'
})

// 详情弹窗
const showDetailModal = ref(false)
const currentDetail = ref(null)

// 统计周期选择处理
const onPeriodChange = (e) => {
  filters.periodIndex = parseInt(e.detail.value)
}

// 交易类型选择处理
const onTransactionTypeChange = (e) => {
  filters.transactionTypeIndex = parseInt(e.detail.value)
}

// 查询数据
const searchData = () => {
  if (paging.value) {
    paging.value.reload()
  }
}

// 重置筛选条件
const resetFilters = () => {
  filters.periodIndex = 0
  filters.transactionTypeIndex = -1
  
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
}

// 查询列表数据
const queryList = (pageNo, pageSize) => {
  // 模拟请求延迟
  setTimeout(() => {
    // 生成模拟数据
    const data = generateMockData(pageNo, pageSize)
    paging.value.complete(data)
    
    // 更新统计摘要
    updateSummary(data)
  }, 500)
}

// 更新统计摘要
const updateSummary = (data) => {
  // 计算总金额和总次数
  let totalAmount = 0
  let totalCount = 0
  
  data.forEach(item => {
    // 计算总交易金额和笔数
    if (item.transactionType === 'refund') {
      totalAmount -= parseFloat(item.amount)
    } else {
      totalAmount += parseFloat(item.amount)
    }
    
    totalCount += item.count
  })
  
  // 计算平均金额
  const avgAmount = totalCount > 0 ? Math.abs(totalAmount / totalCount).toFixed(2) : '0.00'
  
  // 更新摘要数据
  summary.totalAmount = totalAmount.toFixed(2) + '元'
  summary.totalCount = totalCount + '笔'
  summary.avgAmount = avgAmount + '元'
}

// 生成模拟数据
const generateMockData = (pageNo, pageSize) => {
  const data = []
  
  // 停车场列表
  const parkingLots = ["A区停车场", "B区停车场", "C区停车场", "D区停车场", "临时停车场"]
  
  // 时段分布
  const timeDistributions = [
    { name: '早上(6:00-10:00)', value: 'morning' },
    { name: '中午(10:00-14:00)', value: 'noon' },
    { name: '下午(14:00-18:00)', value: 'afternoon' },
    { name: '晚上(18:00-22:00)', value: 'evening' },
    { name: '深夜(22:00-6:00)', value: 'night' }
  ]
  
  // 筛选交易类型
  let filteredTransactionTypes = ['payment', 'refund']
  if (filters.transactionTypeIndex > 0) { // 0是全部，大于0才需要筛选
    filteredTransactionTypes = [transactionTypes[filters.transactionTypeIndex].value]
  }
  
  // 支付类型 - 使用所有类型
  let filteredPaymentTypes = [...paymentTypes]
  
  // 计算总金额和总次数（用于计算占比）
  const totalPaymentAmount = Math.floor(Math.random() * 50000) + 10000 // 10000-60000元
  const totalPaymentCount = Math.floor(Math.random() * 1000) + 500 // 500-1500笔
  const totalRefundAmount = Math.floor(Math.random() * 10000) + 2000 // 2000-12000元
  const totalRefundCount = Math.floor(Math.random() * 200) + 50 // 50-250笔
  
  // 总交易金额和笔数
  const totalAmount = totalPaymentAmount + totalRefundAmount
  const totalCount = totalPaymentCount + totalRefundCount
  
  // 生成随机数据
  for (const paymentType of filteredPaymentTypes) {
    for (const transactionType of filteredTransactionTypes) {
      // 根据交易类型确定金额和次数分布
      let amount, count, baseAmount, baseCount
      
      if (transactionType === 'payment') {
        // 支付金额和次数
        baseAmount = totalPaymentAmount
        baseCount = totalPaymentCount
      } else {
        // 退款金额和次数
        baseAmount = totalRefundAmount
        baseCount = totalRefundCount
      }
      
      // 根据支付类型设置不同的分布
      let amountPercentage, countPercentage
      
      if (paymentType.value === 'wechat') {
        amountPercentage = Math.random() * 0.2 + 0.3 // 30%-50%
        countPercentage = Math.random() * 0.2 + 0.3 // 30%-50%
      } else if (paymentType.value === 'alipay') {
        amountPercentage = Math.random() * 0.15 + 0.2 // 20%-35%
        countPercentage = Math.random() * 0.15 + 0.2 // 20%-35%
      } else if (paymentType.value === 'wallet') {
        amountPercentage = Math.random() * 0.1 + 0.1 // 10%-20%
        countPercentage = Math.random() * 0.1 + 0.1 // 10%-20%
      } else if (paymentType.value === 'card') {
        amountPercentage = Math.random() * 0.1 + 0.05 // 5%-15%
        countPercentage = Math.random() * 0.1 + 0.05 // 5%-15%
      } else {
        amountPercentage = Math.random() * 0.05 + 0.02 // 2%-7%
        countPercentage = Math.random() * 0.05 + 0.02 // 2%-7%
      }
      
      amount = Math.floor(baseAmount * amountPercentage)
      count = Math.floor(baseCount * countPercentage)
      
      // 计算占比（相对于总交易金额和总交易笔数）
      const percentage = ((amount / (transactionType === 'payment' ? totalPaymentAmount : totalRefundAmount)) * 100).toFixed(2)
      
      // 计算平均金额
      const avgAmount = count > 0 ? (amount / count).toFixed(2) : '0.00'
      
      // 生成最高和最低交易金额
      const maxAmount = parseFloat(avgAmount) * (Math.random() * 3 + 2).toFixed(2) // 平均金额的2-5倍
      const minAmount = parseFloat(avgAmount) * (Math.random() * 0.5 + 0.1).toFixed(2) // 平均金额的10%-60%
      
      // 生成停车场分布
      const parkingLotDetails = []
      let remainingLotCount = count
      
      for (let j = 0; j < parkingLots.length; j++) {
        let lotCount
        if (j === parkingLots.length - 1) {
          lotCount = remainingLotCount
        } else {
          lotCount = Math.floor(count * (Math.random() * 0.4 + 0.1)) // 10%-50%
          remainingLotCount -= lotCount
        }
        
        const lotPercentage = ((lotCount / count) * 100).toFixed(2)
        
        parkingLotDetails.push({
          name: parkingLots[j],
          count: lotCount,
          percentage: lotPercentage
        })
      }
      
      // 生成时段分布
      const timeDistributionDetails = []
      let remainingTimeCount = count
      
      for (let j = 0; j < timeDistributions.length; j++) {
        let timeCount
        if (j === timeDistributions.length - 1) {
          timeCount = remainingTimeCount
        } else {
          timeCount = Math.floor(count * (Math.random() * 0.3 + 0.05)) // 5%-35%
          remainingTimeCount -= timeCount
        }
        
        const timePercentage = ((timeCount / count) * 100).toFixed(2)
        
        timeDistributionDetails.push({
          name: timeDistributions[j].name,
          count: timeCount,
          percentage: timePercentage
        })
      }
      
      // 支付模式和缴费时间数据已移除
      
      // 添加数据
      data.push({
        id: data.length + 1,
        paymentTypeName: paymentType.name,
        paymentTypeValue: paymentType.value,
        iconText: paymentType.iconText,
        iconBgColor: paymentType.iconBgColor,
        transactionType: transactionType,
        amount: amount.toFixed(2),
        count,
        percentage,
        avgAmount,
        maxAmount,
        minAmount,
        parkingLots: parkingLotDetails,
        timeDistribution: timeDistributionDetails
      })
    }
  }
  
  // 根据金额排序（从多到少）
  return data.sort((a, b) => parseFloat(b.amount) - parseFloat(a.amount))
}

// 打开详情弹窗
const openDetail = (item) => {
  // 移除不需要的字段
  const { paymentMode, paymentTime, paymentModeDistribution, paymentTimeDistribution, ...rest } = item
  currentDetail.value = rest
  showDetailModal.value = true
}

// 页面加载
onMounted(() => {
  // 页面挂载时获取数据
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
})
</script>

<style lang="scss" scoped>
.payment-type-stats-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.list-paging {
  flex: 1;
  height: 100%;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
  }
}

.filter-section {
  background: white;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .filter-row {
    display: flex;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .filter-item {
    flex: 1;
    margin-right: 20rpx;
    
    &:last-child {
      margin-right: 0;
    }
    
    &.full-width {
      flex: none;
      width: 100%;
      margin-right: 0;
    }
  }
  
  .filter-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    display: block;
  }
  
  .date-picker,
  .picker-input {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 10rpx;
    background: #fafafa;
    font-size: 26rpx;
    color: #666;
  }
  
  .filter-actions {
    display: flex;
    gap: 20rpx;
    margin-top: 30rpx;
  }
  
  .search-btn,
  .reset-btn {
    flex: 1;
    padding: 20rpx;
    border-radius: 10rpx;
    font-size: 28rpx;
    border: none;
  }
  
  .search-btn {
    background: #1890FF;
    color: white;
  }
  
  .reset-btn {
    background: #f0f0f0;
    color: #666;
  }
}

.summary-section {
  display: flex;
  justify-content: space-between;
  margin: 0 20rpx 20rpx;
  
  .summary-card {
    flex: 1;
    background: white;
    border-radius: 10rpx;
    padding: 20rpx;
    margin: 0 10rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    text-align: center;
    
    &:first-child {
      margin-left: 0;
    }
    
    &:last-child {
      margin-right: 0;
    }
    
    .summary-title {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
    }
    
    .summary-value {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }
}

.list-header {
  display: flex;
  background: #f0f0f0;
  padding: 20rpx;
  margin: 0 20rpx;
  border-radius: 10rpx 10rpx 0 0;
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
}

.list-row {
  display: flex;
  background: white;
  padding: 20rpx;
  margin: 0 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
  font-size: 26rpx;
  color: #666;
  
  &:last-child {
    border-radius: 0 0 10rpx 10rpx;
    margin-bottom: 20rpx;
  }
}

.list-cell {
  flex: 1;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 0 5rpx;
  font-size: 24rpx;
}

.payment-cell {
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-icon {
  width: 30rpx;
  height: 30rpx;
  border-radius: 6rpx;
  margin-right: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20rpx;
}

.transaction-cell {
  display: flex;
  align-items: center;
  justify-content: center;
}

.transaction-tag {
  padding: 4rpx 10rpx;
  border-radius: 6rpx;
  font-size: 20rpx;
  color: white;
}

.payment-tag {
  background-color: #07C160;
}

.refund-tag {
  background-color: #FF3B30;
}

.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.detail-content {
  width: 80%;
  max-height: 80%;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #f5f5f5;
  border-bottom: 2rpx solid #e0e0e0;
  
  .detail-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .close-btn {
    font-size: 40rpx;
    color: #999;
    line-height: 1;
  }
}

.detail-body {
  padding: 30rpx;
  overflow-y: auto;
}

.detail-item {
  display: flex;
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .detail-label {
    width: 200rpx;
    font-size: 28rpx;
    color: #666;
  }
  
  .detail-value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
}

.payment-detail {
  display: flex;
  align-items: center;
}

.lot-item,
.time-item {
  margin-bottom: 10rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}
</style>